<template>
  <div class="agent-rank-container">
    <!-- 搜索栏 -->
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-input v-model="searchForm.keyword" placeholder="经纪人ID/姓名/手机号" clearable @keyup.enter="handleSearch">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.level" placeholder="经纪人级别" clearable style="width: 120px">
            <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 排行榜卡片 -->
    <el-card class="rank-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>经纪人业绩排行榜</span>
          <div class="rank-tabs">
            <el-radio-group v-model="rankType" @change="handleRankTypeChange">
              <el-radio-button label="total">总业绩</el-radio-button>
              <el-radio-button label="transaction">交易类</el-radio-button>
              <el-radio-button label="non-transaction">非交易类</el-radio-button>
              <el-radio-button label="assist">助贷类</el-radio-button>
            </el-radio-group>
          </div>
          <el-button type="primary" @click="exportRanking">
            <el-icon>
              <Download />
            </el-icon>
            <span>导出排行</span>
          </el-button>
        </div>
      </template>

      <!-- 排行榜表格 -->
      <el-table v-loading="loading" :data="rankList" border style="width: 100%">
        <el-table-column type="index" label="排名" width="80" align="center">
          <template #default="{ $index }">
            <template v-if="$index < 3">
              <el-tag :type="getRankTagType($index)">{{ $index + 1 }}</el-tag>
            </template>
            <template v-else>{{ $index + 1 }}</template>
          </template>
        </el-table-column>
        <el-table-column label="经纪人信息" min-width="200">
          <template #default="{ row }">
            <div class="agent-info">
              <el-avatar :size="40" :src="row.avatar || defaultAvatar" />
              <div class="agent-details">
                <div class="agent-name">{{ row.name }}</div>
                <div class="agent-id">ID: {{ row.id }}</div>
                <div class="agent-level">
                  <el-tag :type="getLevelTagType(row.level)" size="small">
                    {{ getLevelName(row.level) }}
                  </el-tag>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="总业务量" align="center">
          <template #default="{ row }">
            <div class="count-value">{{ row.totalCount }}笔</div>
          </template>
        </el-table-column>
        <el-table-column label="总放款金额" align="center">
          <template #default="{ row }">
            <div class="amount-value">￥{{ formatAmount(row.totalAmount) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="交易类产品" align="center" v-if="rankType === 'total' || rankType === 'transaction'">
          <template #default="{ row }">
            <div class="count-value">{{ row.transactionCount }}笔</div>
            <div class="amount-value">￥{{ formatAmount(row.transactionAmount) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="非交易类产品" align="center" v-if="rankType === 'total' || rankType === 'non-transaction'">
          <template #default="{ row }">
            <div class="count-value">{{ row.nonTransactionCount }}笔</div>
            <div class="amount-value">￥{{ formatAmount(row.nonTransactionAmount) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="助贷类产品" align="center" v-if="rankType === 'total' || rankType === 'assist'">
          <template #default="{ row }">
            <div class="count-value">{{ row.assistCount }}笔</div>
            <div class="amount-value">￥{{ formatAmount(row.assistAmount) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="直客收入占比" align="center" width="120">
          <template #default="{ row }">
            <el-progress :percentage="row.directCustomerRatio" :color="getProgressColor(row.directCustomerRatio)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewAgentDetail(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 经纪人详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="经纪人详情" width="800px">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="经纪人ID" :span="1">{{ currentAgent.id }}</el-descriptions-item>
        <el-descriptions-item label="姓名" :span="1">{{ currentAgent.name }}</el-descriptions-item>
        <el-descriptions-item label="性别" :span="1">{{ currentAgent.gender === 1 ? '男' : '女' }}</el-descriptions-item>
        <el-descriptions-item label="出生日期" :span="1">{{ currentAgent.birthdate }}</el-descriptions-item>
        <el-descriptions-item label="工作性质" :span="1">{{ currentAgent.workType }}</el-descriptions-item>
        <el-descriptions-item label="教育水平" :span="1">{{ currentAgent.education }}</el-descriptions-item>
        <el-descriptions-item label="直客收入占比" :span="1">{{ currentAgent.directCustomerRatio }}%</el-descriptions-item>
        <el-descriptions-item label="总业务量" :span="1">{{ currentAgent.totalCount }}笔</el-descriptions-item>
        <el-descriptions-item label="总放款金额" :span="1">￥{{ formatAmount(currentAgent.totalAmount)
          }}</el-descriptions-item>
      </el-descriptions>

      <div class="detail-section">
        <div class="section-title">业绩构成</div>
        <el-table :data="performanceData" border style="width: 100%; margin-top: 10px;">
          <el-table-column prop="type" label="业务类型" width="150" />
          <el-table-column prop="count" label="业务笔数" width="120" align="center" />
          <el-table-column prop="amount" label="放款金额" min-width="120" align="center">
            <template #default="{ row }">
              ￥{{ formatAmount(row.amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="ratio" label="占比" width="150" align="center">
            <template #default="{ row }">
              <el-progress :percentage="row.ratio" :color="getProgressColor(row.ratio)" />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="detail-section">
        <div class="section-title">月度业绩趋势</div>
        <div ref="chartRef" class="performance-chart"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { Search, Download } from '@element-plus/icons-vue';
import * as echarts from 'echarts';

defineOptions({
  name: "AgentRank"
});

const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 搜索表单
const searchForm = reactive({
  keyword: '',
  level: '',
  dateRange: [] as string[]
});

// 级别选项
const levelOptions = [
  { label: '全部', value: '' },
  { label: '初级', value: '1' },
  { label: '中级', value: '2' },
  { label: '高级', value: '3' }
];

// 排名类型
const rankType = ref('total');

// 加载状态
const loading = ref(false);

// 排行榜数据
const rankList = ref([]);

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 当前查看的经纪人
const currentAgent = ref({
  id: '',
  name: '',
  gender: 1,
  birthdate: '',
  avatar: '',
  workType: '',
  education: '',
  directCustomerRatio: 0,
  totalCount: 0,
  totalAmount: 0,
  transactionCount: 0,
  transactionAmount: 0,
  nonTransactionCount: 0,
  nonTransactionAmount: 0,
  assistCount: 0,
  assistAmount: 0
});

// 详情对话框
const detailDialogVisible = ref(false);
const chartRef = ref();
let performanceChart: any = null;

// 业绩构成数据
const performanceData = computed(() => {
  return [
    {
      type: '交易类产品',
      count: currentAgent.value.transactionCount,
      amount: currentAgent.value.transactionAmount,
      ratio: Math.round((currentAgent.value.transactionAmount / (currentAgent.value.totalAmount || 1)) * 100)
    },
    {
      type: '非交易类产品',
      count: currentAgent.value.nonTransactionCount,
      amount: currentAgent.value.nonTransactionAmount,
      ratio: Math.round((currentAgent.value.nonTransactionAmount / (currentAgent.value.totalAmount || 1)) * 100)
    },
    {
      type: '助贷类产品',
      count: currentAgent.value.assistCount,
      amount: currentAgent.value.assistAmount,
      ratio: Math.round((currentAgent.value.assistAmount / (currentAgent.value.totalAmount || 1)) * 100)
    }
  ];
});

// 加载排行榜数据
const loadRankingData = () => {
  loading.value = true;

  // 模拟API请求，实际项目中应该调用真实API
  setTimeout(() => {
    // 生成模拟数据
    const mockAgents = Array.from({ length: 20 }, (_, index) => {
      const id = 10000 + index;
      const level = Math.floor(Math.random() * 3) + 1;
      const transactionCount = Math.floor(Math.random() * 20) + 5;
      const transactionAmount = (Math.floor(Math.random() * 500) + 100) * 10000;
      const nonTransactionCount = Math.floor(Math.random() * 15) + 3;
      const nonTransactionAmount = (Math.floor(Math.random() * 300) + 50) * 10000;
      const assistCount = Math.floor(Math.random() * 10) + 2;
      const assistAmount = (Math.floor(Math.random() * 200) + 30) * 10000;

      return {
        id,
        name: `经纪人${id}`,
        gender: Math.random() > 0.5 ? 1 : 2,
        birthdate: `199${Math.floor(Math.random() * 9)}-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1}`,
        avatar: `https://randomuser.me/api/portraits/${Math.random() > 0.5 ? 'men' : 'women'}/${Math.floor(Math.random() * 100)}.jpg`,
        level,
        workType: Math.random() > 0.3 ? '全职' : '兼职',
        education: ['大专', '本科', '硕士'][Math.floor(Math.random() * 3)],
        directCustomerRatio: Math.floor(Math.random() * 80) + 20,
        transactionCount,
        transactionAmount,
        nonTransactionCount,
        nonTransactionAmount,
        assistCount,
        assistAmount,
        totalCount: transactionCount + nonTransactionCount + assistCount,
        totalAmount: transactionAmount + nonTransactionAmount + assistAmount
      };
    });

    // 根据排名类型排序
    mockAgents.sort((a, b) => {
      if (rankType.value === 'total') {
        return b.totalAmount - a.totalAmount;
      } else if (rankType.value === 'transaction') {
        return b.transactionAmount - a.transactionAmount;
      } else if (rankType.value === 'non-transaction') {
        return b.nonTransactionAmount - a.nonTransactionAmount;
      } else if (rankType.value === 'assist') {
        return b.assistAmount - a.assistAmount;
      }
      return 0;
    });

    // 筛选处理
    let filteredAgents = [...mockAgents];

    if (searchForm.keyword) {
      const keyword = searchForm.keyword.toLowerCase();
      filteredAgents = filteredAgents.filter(agent =>
        agent.id.toString().includes(keyword) ||
        agent.name.toLowerCase().includes(keyword)
      );
    }

    if (searchForm.level) {
      filteredAgents = filteredAgents.filter(agent =>
        agent.level.toString() === searchForm.level
      );
    }

    // 分页处理
    const startIndex = (pagination.currentPage - 1) * pagination.pageSize;
    const endIndex = startIndex + pagination.pageSize;

    rankList.value = filteredAgents.slice(startIndex, endIndex);
    pagination.total = filteredAgents.length;

    loading.value = false;
  }, 600);
};

// 处理排名类型变更
const handleRankTypeChange = () => {
  loadRankingData();
};

// 获取排名标签类型
const getRankTagType = (index: number) => {
  const types = ['danger', 'warning', 'success'];
  return types[index] || 'info';
};

// 获取经纪人等级名称
const getLevelName = (level: number) => {
  switch (level) {
    case 1: return '初级';
    case 2: return '中级';
    case 3: return '高级';
    default: return '未知';
  }
};

// 获取经纪人等级标签类型
const getLevelTagType = (level: number) => {
  switch (level) {
    case 1: return 'info';
    case 2: return 'success';
    case 3: return 'danger';
    default: return 'info';
  }
};

// 格式化金额
const formatAmount = (amount: number) => {
  if (amount >= 10000) {
    return (amount / 10000).toFixed(2) + '万';
  }
  return amount.toLocaleString();
};

// 获取进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage < 30) {
    return '#909399';
  } else if (percentage < 60) {
    return '#e6a23c';
  } else {
    return '#67c23a';
  }
};

// 查看经纪人详情
const viewAgentDetail = (agent) => {
  currentAgent.value = { ...agent };
  detailDialogVisible.value = true;

  // 在对话框打开后初始化图表
  nextTick(() => {
    initPerformanceChart();
  });
};

// 初始化业绩图表
const initPerformanceChart = () => {
  if (!chartRef.value) return;

  performanceChart = echarts.init(chartRef.value);

  // 生成假数据 - 最近6个月
  const months = [];
  const transactionData = [];
  const nonTransactionData = [];
  const assistData = [];

  for (let i = 5; i >= 0; i--) {
    const date = new Date();
    date.setMonth(date.getMonth() - i);
    months.push(`${date.getFullYear()}-${date.getMonth() + 1}`);

    transactionData.push(Math.floor(Math.random() * 300000) + 100000);
    nonTransactionData.push(Math.floor(Math.random() * 200000) + 50000);
    assistData.push(Math.floor(Math.random() * 150000) + 30000);
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params) {
        let result = `${params[0].axisValue}<br/>`;
        params.forEach(item => {
          result += `${item.seriesName}: ￥${(item.value / 10000).toFixed(2)}万<br/>`;
        });
        return result;
      }
    },
    legend: {
      data: ['交易类产品', '非交易类产品', '助贷类产品']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: function (value) {
          return (value / 10000) + '万';
        }
      }
    },
    series: [
      {
        name: '交易类产品',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: transactionData
      },
      {
        name: '非交易类产品',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: nonTransactionData
      },
      {
        name: '助贷类产品',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: assistData
      }
    ]
  };

  performanceChart.setOption(option);
};

// 导出排行榜
const exportRanking = () => {
  ElMessage.success('排行榜数据导出中，请稍候...');
  // 实际项目中应该调用导出API
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  loadRankingData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.level = '';
  searchForm.dateRange = [];
  pagination.currentPage = 1;
  loadRankingData();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  loadRankingData();
};

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadRankingData();
};

// 页面挂载时加载数据
onMounted(() => {
  loadRankingData();
});
</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.search-card :deep(.el-form) {
  display: flex;
  flex-wrap: wrap;
}

.rank-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rank-tabs {
  margin-left: auto;
  margin-right: 16px;
}

.agent-info {
  display: flex;
  align-items: center;
}

.agent-details {
  margin-left: 10px;
}

.agent-name {
  font-weight: bold;
  margin-bottom: 3px;
}

.agent-id {
  color: #909399;
  font-size: 13px;
  margin-bottom: 3px;
}

.agent-level {
  margin-top: 3px;
}

.count-value {
  font-weight: bold;
  margin-bottom: 3px;
}

.amount-value {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.detail-section {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.performance-chart {
  width: 100%;
  height: 400px;
  margin-top: 10px;
}

:deep(.el-table th.el-table__cell) {
  background-color: var(--el-table-header-bg-color);
  color: var(--el-text-color-primary);
  font-weight: 500;
}
</style>